import { join } from 'path';
// 加载插件模块
const loadPluginModules = (data: any) => {
	let resPliugin = []
	for (const [, value] of Object.entries(data)) {
		resPliugin.push(value)
	}
	return resPliugin
};

// 基本配置
const baseCfg = (farmEnv = {}) => {
	return {
		envDir: 'farm-env',
		server: {
			host: 'localhost', // 服务器主机名，如果允许外部访问，可设置为"0.0.0.0"
			port: 9000,
			open: false,
			cors: true,
		},
		compilation: {
			resolve: {
				alias: {
					'@/': join(process.cwd(), 'src')
				}
			}
		}
	};
};

// 处理加载的插件模块
const hanldePluginModules = async (pluginsArr: any = [], farmEnv: any) => {
	let resModule: any = []
	pluginsArr.forEach((item: any) => {
		const funcs = Object.values(item);
		funcs.forEach((it: any) => {
			if (typeof it === "function") {
				resModule.push(it(farmEnv));
			}
		});
	});
	return resModule
};

// 插件配置
const pluginCfg = async (farmEnv: any = {}) => {
	const loadFarmPlugins = await import.meta.glob("./farmPlugins/*.ts", { eager: true });
	const loadVitePlugins = await import.meta.glob("./vitePlugins/*.ts", { eager: true });
	const loadFarm = loadPluginModules(loadFarmPlugins);
	const loadVite = loadPluginModules(loadVitePlugins);
	const farmPlugins = await hanldePluginModules(loadFarm, farmEnv);
	const vitePlugins = await hanldePluginModules(loadVite, farmEnv);
	return {
		farmPlugin: farmPlugins,
		vitePlugin: vitePlugins
	};
};

export { baseCfg, pluginCfg };
